package com.collection.web.resolver;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.collection.web.pagination.PageRequest;
import com.collection.web.resolver.annotation.GridParam;


@Component
public class PageableHandlerMethodArgumentResolver implements
		HandlerMethodArgumentResolver {
	 private static final Logger      logger        = LoggerFactory.getLogger(PageableHandlerMethodArgumentResolver.class);
	private static final String PARAM_PAGE_NUM="page";
	private static final String PARAM_PAGE_SIZE="rows";
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(GridParam.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		try {
			int pageNum =NumberUtils.toInt(webRequest.getParameter(PARAM_PAGE_NUM));
			int pageSize =NumberUtils.toInt(webRequest.getParameter(PARAM_PAGE_SIZE));
			return new PageRequest(pageNum, pageSize);
		} catch (Exception e) {
			logger.error("构建分页请求对象出错",e);
			return new PageRequest();
		}
	}

}
